#!/bin/bash

#
# gompile -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# Fast compiles a source file that contains in the first 10 lines the magic
# string "Compile command: " followed by a command to use.
#
# The special variables are: $SRC for the source name, and $SRC_NOEXT for the
# source name without extension.
#

#
# Globals
#

# Search within the first # lines
export FIRSTLINES=10

#
# Functions
#

# Main function
function Main() {

  local SRC="$1"
  local SRC_NOEXT=${SRC%.*}
  local CMDRAW
  local CMD

  if [ "$SRC" == "" ]; then
    echo "Usage: $0 <source_file>"
    exit 1
  elif [ ! -r "$SRC" ]; then
    echo "No such file: $SRC"
    exit 2
  fi

  CMDRAW=`head -n$FIRSTLINES "$SRC" | grep "Compile command: " | head -n1`

  if [ "$CMDRAW" == "" ]; then
    echo "$SRC: no builtin command found."
    echo "You must write within the first $FIRSTLINES lines of $SRC something like:"
    echo -e "\033[1;35m/* Compile command: mycc --output \$SRC_NOEXT \$SRC */\033[m"
    exit 3
  fi

  CMD=`echo "$CMDRAW" | perl -ne '/Compile command:\s+(.*)$/; print "$1\n"'`

  echo -e "\033[1;35mExecuting \033[1;33m`eval echo $CMD`\033[1;35m...\033[m"
  eval "$CMD"
  exit $?

}

#
# Entry point
#

Main "$@"
